import { FishProviderProps } from "fish-ui-yy"
import React from "react"
import { createCSSRuleFromTheme } from "./createCSSRuleFromTheme";


// 生成style标签，创建到head下面
const createStyleTag = ( target:Document | undefined,elementAttributes:Record<string,string>) =>{
   if(!target){
    return undefined
   }
   const tag = target.createElement("style");
   Object.keys(elementAttributes).forEach((attrName) =>{
        tag.setAttribute(attrName,elementAttributes[attrName])
   })
   target.head.appendChild(tag)
   return tag
}


// 将rule插入到style里
const insertRuleToStyle = (tag:HTMLStyleElement,rule:string) =>{
    const sheet = tag.sheet;
    if(sheet){
        if(sheet.cssRules.length > 0){
            sheet.deleteRule(0)
        }
        sheet.insertRule(rule)
    }
}

/**
 * 
 * @param param0 
 * @returns 
 * 将them传递过来之后，因为每个样式theme都会走一遍这个方法，将每个组件用Id识别
 * 将传递过来的theme格式化成能识别的样式，并且创建style，插入到theme
 */

export const useThemeStyleTag = ({theme}:Partial<FishProviderProps>)=>{
    const generatedId = React.useId()
    const escapedId = React.useMemo(
        ()=>
        {return generatedId.replace(/:/g, "")}
    ,[generatedId]);
    // 这个是唯一类名，为了确保主题只作用在各自的子组件上
    const themeClassName = "fish-ui-FishProvider" + escapedId;
    // 这里根据theme生成rule
    const rule = React.useMemo(()=>{return createCSSRuleFromTheme(`.${themeClassName}`,theme)},[themeClassName,theme])
    // 下面是创建style标签插入到header
    const styleTag = React.useRef<HTMLStyleElement | undefined | null>(null);
    React.useLayoutEffect(()=>{
        styleTag.current = createStyleTag(document,{id:themeClassName})
        // 将rule插入到style标签
        if(styleTag.current){
            insertRuleToStyle(styleTag.current,rule)
        }
        return () =>{
            styleTag.current?.remove()
        }
    },[themeClassName,rule])
    return ({themeClassName})
}
